package com.example.threaddemo;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author wdl
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvInfoText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvInfoText = findViewById(R.id.tv_info_text);
        Button btnTest = findViewById(R.id.btn_test);
        Button btnTest2 = findViewById(R.id.btn_test1);
        Button btnAsyncTask = findViewById(R.id.btn_async_task);

        btnTest.setOnClickListener(this);
        btnTest2.setOnClickListener(this);
        btnAsyncTask.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_test:
                //在主线程直接更新UI是错误的示范
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        tvInfoText.setText("错误示范");
                    }
                });
                thread.start();
                break;
            case R.id.btn_test1:
                Thread thread1 = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //使用Runnable()封住UI更新的的代码
                        Runnable updateUIControl = new Runnable() {
                            @Override
                            public void run() {
                                tvInfoText.setText("更新TextView的显示信息");
                            }
                        };
                        //以下三种均可以跨线程更新UI
                        MainActivity.this.runOnUiThread(updateUIControl);
//                        tvInfoText.post(updateUIControl);
//                        tvInfoText.postDelayed(updateUIControl,3000);
                    }
                });
                thread1.start();
                break;
            case R.id.btn_async_task:
                /*
                实例化一个task,调用execute开始执行
                 */
                MyAsyncTask myAsyncTask=new MyAsyncTask();
                myAsyncTask.execute(100);
                break;
            default:
        }
    }

    private class MyAsyncTask extends AsyncTask<Integer, Integer, Integer> {
        /**
         * 用于显示进度的对话框
         */
        private ProgressDialog infoProgressDialog = null;

        /**
         * 进度弹窗的设置
         */
        private void setInfoProgressDialog() {
            infoProgressDialog = new ProgressDialog(MainActivity.this);
            infoProgressDialog.setTitle("正在处理");
            infoProgressDialog.setCancelable(true);
            infoProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            infoProgressDialog.setMessage("准备开始后台工作..");
            infoProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    MyAsyncTask.this.cancel(true);
                }
            });
            infoProgressDialog.setCanceledOnTouchOutside(true);
            infoProgressDialog.show();
        }

        /**
         * 在doInBackground之前调用
         * 主要做一些初始化的工作在UI线程中执行
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            setInfoProgressDialog();
        }

        /**
         * 后台运行的代码(工作的代码写在此处)
         * 封装异步执行的方法
         */
        @Override
        protected Integer doInBackground(Integer... integers) {
            //integers保存了通过execute()传过来的参数
            int sleepTime = integers[0];
            int result = 0;
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(sleepTime);
                    result ++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                /*
                每五次更新一次,防止更新太过频繁
                * */
                if (i % 5 == 0) {
                    /*
                    通过publishProgress可以更新UI
                     */
                    publishProgress(result);
                }
                /*
                判断外界是否取消,取消则停止
                 */
                if (isCancelled()) {
                    break;
                }
            }
            return result;
        }

        /**
         * 工作过程中调用publishProgress()时调用这个方法,在UI线程中执行
         *
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            infoProgressDialog.setTitle("已经完成" + values[0] + "%");
            infoProgressDialog.setProgress(values[0]);
        }

        /**
         * 工作完成后调用这个方法,在UI线程中执行
         *
         * @param integer
         */
        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            /*
            完成工作后取消
             */
            tvInfoText.setText("异步工作已经完成");
            infoProgressDialog.dismiss();
        }

        /**
         * 外界提出取消操作请求的时候调用
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
            tvInfoText.setText("工作被取消");
            infoProgressDialog.dismiss();
        }
    }
}
